package com.caseProcess.controller;

import com.caseProcess.entity.Resources;
import com.caseProcess.entity.Result;
import com.caseProcess.service.ResourcesService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author kittlen
 * @version 1.0
 * @date 2020/11/22 13:13
 */
@Controller
@RequestMapping("/fileDown")
public class FIleDownController {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Resource
    private ResourcesService resourcesService;

    /**
     * 文件下载
     * @param resourcesId 文件ID
     * @param response
     * @throws Exception
     */
    @RequestMapping("/downloadFileByResId")
    public void downloadFile(String resourcesId, HttpServletResponse response, HttpServletRequest request) {
        Resources resources=new Resources();
        resources.setResourcesId(resourcesId);
        List<Resources> list=resourcesService.selectResourcess(resources);
        if(!list.isEmpty()){
            Resources outRes=list.get(0);
            String filename = outRes.getResourcesName();
            //获取当前资源的虚拟路径
//            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            String path = getPath();
            path +="classes";
            path += outRes.getResourcesUrl();
            //获取输入流
            InputStream bis = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(new File(path)));
            //转码，免得文件名中文乱码
            filename = URLEncoder.encode(filename, "UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            //设置文件ContentType类型，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            while ((len = bis.read()) != -1) {
                out.write(len);
                out.flush();
            }
            out.close();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                try {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html;charset=UTF-8");
                    response.setHeader("contentType", "text/html; charset=utf-8");
                    response.getWriter().write("文件异常,下载失败");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }

            }
        }

    }

    public String getPath(){
        URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
        String path = url.toString();
        int index = path.indexOf("WebRoot");

        if(index == -1){
            index = path.indexOf("classes");
        }

        if(index == -1){
            index = path.indexOf("bin");
        }

        path = path.substring(0, index);

        if(path.startsWith("zip")){//当class文件在war中时，此时返回zip:D:/...这样的路径
            path = path.substring(4);
        }else if(path.startsWith("file")){//当class文件在class文件中时，此时返回file:/D:/...这样的路径
            path = path.substring(6);
        }else if(path.startsWith("jar")){//当class文件在jar文件里面时，此时返回jar:file:/D:/...这样的路径
            path = path.substring(10);
        }
        try {
            path =  URLDecoder.decode(path, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return path;

    }

    @ResponseBody
    @RequestMapping("deleteById")
    public Result deleteById(String resourcesId,String resourcesUrl){
        Result result=new Result();
        Resources resources=new Resources();
        resources.setResourcesId(resourcesId);
        String path = getPath();
        path +="classes";
        path += resourcesUrl;
        File file =new File(path);
        if(file.exists()){
            file.delete();
        }
        resourcesService.delete(resources);
        return result;
    }
}
